package com.xsk.dou.core.api

import com.xsk.dou.model.Response
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory


interface Action<Enty, T> {
    fun doAction(api: T): Observable<Response<Enty>>
}

class NetWorkManager private constructor() {
    companion object {
        val manager = Holder.manager
        val BASE_URL: String = "https://douban.uieee.com/v2/movie/"

    }

    object Holder {
        val manager = NetWorkManager()
    }

    private val client = OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor()).build()


    private val retrofit = Retrofit.Builder()
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .baseUrl(BASE_URL)
        .build()

    fun <En, T> create(
        api: Class<T>,
        action: Action<En, T>
    ): Observable<Response<En>> {

        val tmpApi = retrofit.create(api)

        return action.doAction(tmpApi).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())

    }
}